package by.epam.xslttask.command;

import by.epam.xslttask.logger.LoggerType;
import by.epam.xslttask.logger.XSLTLogger;
import by.epam.xslttask.managers.LogManager;
import by.epam.xslttask.managers.PathManager;
import javax.servlet.ServletException;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Darya_Hrishanovich
 * Date: 7/6/12
 * Time: 4:55 AM
 * To change this template use File | Settings | File Templates.
 */
public final class ShowXSLCommand extends Command {
    private String elementType;
    private Map<String, String> params;

    public String getElementType() {
        return elementType;
    }

    public void setElementType(String elementType) {
        this.elementType = elementType;
    }
    
    public ShowXSLCommand(String relPath, String elementType, Map<String, String> params) {
        super(relPath);
        this.elementType = elementType;
        this.params = params;
    }

    @Override
    public Map<String, String> execute() throws IOException, ServletException {
        String xml = PathManager.getProperty(PathManager.XML);
        String xsl = getRelPath() + PathManager.getProperty(elementType);
        Transformer t;
        Templates templates;
        try {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Source xslSource = new StreamSource(new File(xsl));
            if(!getMapTemplates().containsKey(xsl)) {
                templates = tFactory.newTemplates(xslSource);
                addTemplates(xsl, templates);
            }
            else {
                templates = getMapTemplates().get(xsl);
            }

            t = templates.newTransformer();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                Object values = entry.getValue();
                String value = ((String[])values)[0];
                t.setParameter(key, value);
            }
            getLock().readLock().lock();
            t.transform(new StreamSource(xml), new StreamResult(getOut()));
        } catch (TransformerException e) {
            String message = LogManager.getProperty(LogManager.TRANSFORM_ERROR);
            XSLTLogger.logMessage(message, ShowXSLCommand.class, LoggerType.ERROR);
            throw new ServletException(e);
        }
        finally {
            getLock().readLock().unlock();
        }
        return null;
    }
}
